/* 
 * File:   RemoveStackCommand.cpp
 * Author: Gab'z
 * 
 * Created on 5 juin 2012, 02:36
 */

#include "RemoveStackCommand.h"
#include "../../Context.h"
#include "../../command/literal/StackList.h"
#include "../../memento/RemoveStackMemento.h"
#include "../../../exception/MementoException.h"

namespace calculator {

    RemoveStackCommand::RemoveStackCommand(const std::string name) : StackListCommand(name) {
    }

    RemoveStackCommand::RemoveStackCommand(const RemoveStackCommand& orig) : StackListCommand(orig._name) {
    }

    RemoveStackCommand::~RemoveStackCommand() {
    }

    RemoveStackCommand* RemoveStackCommand::clone() const {
        return new RemoveStackCommand(_name);
    }

    std::string RemoveStackCommand::isExecutable() const {
        if (Context::getInstance()->getStackList()->size() <= 1) return "Cannot remove one single Stack";
        return "";
    }

    const Memento* RemoveStackCommand::createMemento() const throw (CommandException) {
        return new RemoveStackMemento(clone(),
                Context::getInstance()->getCurrentStack()->clone(),
                Context::getInstance()->getStackList()->getCurrentStackIndex());
    }

    void RemoveStackCommand::restoreFromMemento(const Memento* memento) const throw (MementoException) {
        const RemoveStackMemento* removeStackMemento = dynamic_cast<const RemoveStackMemento*> (memento);
        if (removeStackMemento == 0) {
            std::string str = "Bad Memento type, expected : RemoveStackMemento, was ";
            str += typeid (*memento).name();
            throw MementoException(str);
        } 
        Context::getInstance()->getStackList()->insertStackAtIndex(removeStackMemento->_stack->clone(), removeStackMemento->_stackIndex);
        //Context::getInstance()->getStackList()->setCurrentStack(removeStackMemento->_stackIndex);
    }

    void RemoveStackCommand::apply(StackList* stacklist) const throw (CommandException) {
        if (stacklist->size() == 1) throw CommandException("There must at least one Stack");
        stacklist->removeCurrentStack();
    }
}